<!--车辆终身质保审核 厂端-->
<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" labelWidth="100" :collapse="true" @filterChange="changeHandle" ref="topfilter" @resetChange="resetChange" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      :onSyncTableData="tableChange"
      :onRowSelectChange="selectChange"
      :isExportExcel="true"
      exportFileName="车辆终身质保审核.xlsx"
      :onCalcExportData="handleExportFun"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      datakey="records"
      :isSelectColumn="true"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <!--<multiuse-button type="primary" class="btnStyle" :click="batchReview.bind(this,1)">批量审核</multiuse-button>-->
        <multiuse-button type="primary" class="btnStyle" :click="batchReview.bind(this, 2)">批量驳回</multiuse-button>
        <ajax-button type="primary" class="btnStyle" :click="exportExcel">导出</ajax-button>
      </template>
    </FilterTable>

    <Drawer :visible.sync="visibleDetail" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <detail :warrantyId="warrantyId" @close="closeHandler" :handleType="handleType" />
    </Drawer>

    <BaseDialog :visible.sync="visibleDelear" title="选择经销商" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <add-delear @selectArr="selectDelearFun" @close="closeHandler"></add-delear>
    </BaseDialog>

    <BaseDialog :visible.sync="visibleCarModel" title="选择车型" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <add-car-model @selectArr="selectCarFun" @close="closeHandler"></add-car-model>
    </BaseDialog>

    <BaseDialog :visible.sync="visibleReason" :title="reasonTitle" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <add-reason :batchType="batchType" @inputReason="inputReason" @close="closeHandler"></add-reason>
    </BaseDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import detail from './detail';
import addCarModel from './addCarModel';
import addDelear from './addDelear';
import addReason from './addReason';
import { isEmpty } from '@/utils/utils';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';
import { vehicleWarrantyList, blackAuditAll } from '@/api/repair/newEnergyVehicleLifetime/vehicleLifetimeReviewCDuan';
import { findTableItem, exportExcelFile } from '@/utils';
import { getAllDealer } from '@/api/repair/repairManage/repairQuery/index.js';
import { getAppId } from '@/assets/js/auth';
import { exportExc,exporturl } from '@/api/repair/newEnergyVehicleLifetime/vehicleLifetimeReviewQueryCDuan';

export default {
  name: 'addItem',
  mixins: [dictionary, dealerMixin],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '审核' };
    return {
      topFilterList: this.createTopFilterList(),
      visibleDelear: false,
      visibleDetail: false,
      visibleCarModel: false,
      visibleReason: false,
      fetchApi: vehicleWarrantyList,
      dialogTitle: '',
      reasonTitle: '',
      fetchParams: { xhrAbort: false },
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      warrantyId: '',
      selectArr: [],
      /*表格在中数据*/
      tableData: [],
      batchType: 1,
      selectDealer: null,
      selectCar: null
    };
  },
  components: {
    detail,
    addDelear,
    addCarModel,
    addReason
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    if (getAppId() == 'arcfox') {
      this.columns = this.createTableColumnsArcfox();
      //翻译经销商
      this.getAllDealer();
    } else {
      this.columns = this.createTableColumns();
    }
    // this.getAllUsers(this.columns, ['updatedBy'], 'table');
  },
  methods: {
   async exportExcel() {
      // let json = Object.assign({}, { CODE: 'CODE_00000136' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      this.exportLoading = true;
      exportExc(this.fetchParams)
        .then(response => {
          exportExcelFile(response.data, '车辆终身质保导出');
          this.exportLoading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取所有的经销商
    async getAllDealer() {
      let res = await getAllDealer();
      if (res.resultCode == 200) {
        let allDealer = res.data.map(x => ({ text: x.dealerShortname, value: x.dealerCode + '' }));
        this.columns.find(x => x.dataIndex == 'ownerCode').dictItems = allDealer;
        // this.columns.find(x => x.dataIndex === 'ownerCode').dictItems = allDealer;
      }
    },
    async inputReason(remarks) {
      if (this.batchType == 1) {
        //审核
        // let disabledSelect = this.tableData.filter(row => row.status == '10221001')
        // this.BaseTable.SET_DISABLE_SELECT(disabledSelect)
      } else {
        //驳回
        let newList = [];
        let rejectSelect = this.selectArr.filter(row => row.status != 10221002);
        rejectSelect.forEach(item => {
          let params = {
            warrantyId: item['warrantyId'],
            remarks: remarks,
            status: '10221002'
          };
          newList.push(params);
        });

        let res = await blackAuditAll(newList);

        if (res.resultCode == 200 && res.success == true) {
          this.$notify.success({ title: '提示信息', message: '操作成功' });

          this.fetchParams = Object.assign({}, this.fetchParams);
        }
      }
      this.closeHandler();
    },
    dealerTranslate() {
      let userIds = [];
      this.tableData.forEach(item => {
        userIds.push(item.updatedBy);
      });
      if (!userIds.length) return;
      let newUserIds = Array.from(new Set(userIds)); // 数组去重
      this.getNameByIds(this.columns, newUserIds.join(','), ['updatedBy'], 'table');
    },
    tableChange(data) {
      this.tableData = data;
      this.dealerTranslate();
      let disabledSelect = this.tableData.filter(row => row.status == '10221002');
      this.BaseTable.SET_DISABLE_SELECT(disabledSelect);
    },

    /*配置数量发生改变的时候执行*/
    selectChange(val) {
      this.selectArr = val;
    },

    /*选择经销啥昂*/
    selectDelearFun(arr) {
      let row = arr[0];
      this.selectDealer = row;
      this.topFilterList.find(item => item.fieldName == 'resDealer').initialValue = row['dealerName'];
    },
    /*选择车型*/
    selectCarFun(arr) {
      let row = arr[0];
      console.log('row', row);
      this.selectCar = row;
      this.topFilterList.find(item => item.fieldName == 'model').initialValue = row['modelName'];
    },
    dealerFun() {
      this.visibleDelear = true;
    },

    carModelFun() {
      this.visibleCarModel = true;
    },
    // 导出处理函数
    handleExportFun(row) {
      row.status = this.createDictText(row.status, 1022);
    },
    /*批量审核 1 批量审核 2 批量驳回*/
    batchReview(type) {
      if (this.selectArr.length == 0) {
        this.$notify.warning({ title: '提示信息', message: '请您先选择数据' });
        return;
      }
      this.batchType = type;
      if (type == 1) {
        this.reasonTitle = '请输入审核原因';
      } else {
        this.reasonTitle = '请输入驳回原因';
      }
      this.visibleReason = true;
    },
    detailHandle(row) {
      this.warrantyId = row['warrantyId'];
      this.handleType = 'show';
      this.showHandler();
    },
    createTableColumnsArcfox() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          sorter: true,
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          render: props => {
            let row = props.row;
            let status = isEmpty(row['status']) ? '' : row['status'];
            let rst = false;
            if (status == '10221002') {
              rst = true;
            }
            return (
              <div>
                <multiuse-button
                  type="text"
                  size="mini"
                  // disabled={rst}
                  click={() => this.detailHandle(props.row)}
                >
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '申请状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1022),
          render: props => {
            return <span>{this.createDictText(props.row.status, 1022)}</span>;
          }
        },

        {
          title: '车主姓名',
          dataIndex: 'ownerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '保修起始日期',
          dataIndex: 'salesDate',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '行驶证注册日期',
          dataIndex: 'driveLicenseDate',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '申请日期',
          dataIndex: 'updatedAt',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '申请人',
          dataIndex: 'updatedBy',
          sorter: true,
          dictItems: []
        },
        {
          title: '是否有效',
          dataIndex: 'valid',
          sorter: true,
          dictItems: this.createDictList(1004)
        },
        {
          title: '失效原因',
          dataIndex: 'validReason',
          sorter: true
        },
        {
          title: '申请经销商',
          dataIndex: 'ownerCode',
          dictItems: [],
          sorter: true
        },
        {
          title: '质保类型',
          dataIndex: 'warrantyType',
          // dictItems: this.createDictList('8888'),
          dictItems: this.createDictList('8888'),
          sorter: true
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          sorter: true,
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          render: props => {
            let row = props.row;
            let status = isEmpty(row['status']) ? '' : row['status'];
            let rst = false;
            if (status == '10221002') {
              rst = true;
            }
            return (
              <div>
                <multiuse-button type="text" size="mini" disabled={rst} click={() => this.detailHandle(props.row)}>
                  驳回
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '申请状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1022),
          render: props => {
            return <span>{this.createDictText(props.row.status, 1022)}</span>;
          }
        },
        {
          title: '车主姓名',
          dataIndex: 'ownerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '保修起始日期',
          dataIndex: 'salesDate',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '行驶证注册日期',
          dataIndex: 'driveLicenseDate',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '申请日期',
          dataIndex: 'updatedAt',
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '申请人',
          dataIndex: 'updatedBy',
          sorter: true,
          dictItems: []
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'resDealer',
          placeholder: '请选择',
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.dealerFun()}></el-button>
              </div>
            );
          },
          onInput: e => {
            if (isEmpty(e)) {
              this.selectDealer = null;
            }
          }
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'model',
          placeholder: '请选择',
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.carModelFun()}></el-button>
              </div>
            );
          },
          onInput: e => {
            if (isEmpty(e)) {
              this.selectCar = null;
            }
          }
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: 'VIN...'
        },
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          placeholder: '车主姓名...'
        },
        {
          type: 'INPUT',
          label: '车主电话',
          fieldName: 'mobile',
          placeholder: '车主电话...'
        },
        {
          type: 'RANGE_DATE',
          label: '行驶证注册日期',
          dateType: 'daterange',
          fieldName: 'bDriveLicenseDate|eDriveLicenseDate'
        },
        {
          type: 'RANGE_DATE',
          label: '申请日期',
          dateType: 'daterange',
          fieldName: 'bUpdatedAt|eUpdatedAt'
        }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    resetChange(val) {
      this.selectCar = null;
      this.selectDealer = null;
      console.log(val, 'val');

      // this.$refs.topfilter.RESET_FORM();
      let obj = Object.assign({}, val);
      this.fetchParams = obj;
    },

    changeHandle(val) {
      let obj = Object.assign({}, val);
      let resDealer = isEmpty(this.selectDealer) ? '' : this.selectDealer.dealerCode;
      let model = isEmpty(this.selectCar) ? '' : this.selectCar.modelCode;
      obj['resDealer'] = resDealer;
      obj['model'] = model;
      this.fetchParams = obj;
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}车辆终身质保审核`;

      this.visibleDetail = true;
    },
    closeHandler(type = '') {
      this.visibleReason = false;
      this.visibleDelear = false;
      this.visibleDetail = false;
      this.visibleCarModel = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
